<template>
	<view class="page">
		<view class='distribution-posters' v-if="qrcode">
			<swiper :indicator-dots="indicatorDots" :autoplay="autoplay" :circular="circular" :interval="interval"
				:duration="duration" @change="bindchange" previous-margin="40px" next-margin="40px">
				<block v-for="(item,index) in spreadList" :key="index">
					<swiper-item>
						<image :src="item.pic" class="slide-image" :class="swiperIndex == index ? 'active' : 'quiet'"
							mode='aspectFill' />
					</swiper-item>
				</block>
			</swiper>
			<!-- #ifdef APP-PLUS || MP-->
			<view class='keep' :style="{backgroundColor:bgColor}" @click='savePhoto(spreadList[swiperIndex].pic)'>保存海报</view>
			<!-- #endif -->
			<!-- #ifndef MP || APP-PLUS -->
			<div class="preserve acea-row row-center-wrapper">
				<div class="line"></div>
				<div class="tip">长按保存图片</div>
				<div class="line"></div>
			</div>
			<!-- #endif -->
		</view>
		<view class="canvas" v-if="canvasStatus">
			<canvas style="width:750px;height:1190px;" canvas-id="canvasOne"></canvas>
			<canvas canvas-id="qrcode" :style="{width: `${qrcodeSize}px`, height: `${qrcodeSize}px`}" />
		</view>
		<div class="whiteBg" style="position: fixed;bottom: 60rpx;left: 30rpx;right: 30rpx;display: flex;align-items: center;">
			<div class="invitation-logo bg_color" @click="show= true">设置参数</div>
		</div>
		<neil-modal
			:show="show" 
			title="设置参数" 
			confirm-text="确认"
			confirm-color="#E93323"
			@cancel="show=false" 
			:auto-close="false"
			@confirm="save()"
			>
			<view class="card">
				<view class="item">
					<view class="item-title">添加余额</view>
					<view class='item-input'>
						<input style="width: 100%;" type='number' placeholder="请填写转入的赠送水票数量" name='name' v-model='addCount' maxlength="9"></input>
					</view>
				</view>
				<view class="item">
					<view class="item-title">新人领取</view>
					<view class='item-input'>
						<input style="width: 100%;" type='number' placeholder="请填写新用户领取的赠送水票数量" name='name' v-model='grantCount' maxlength="9"></input>
					</view>
				</view>
				<view class="tips">
					<view>*当前赠送水票余额:</view>
					<view style="color: #FB8C00;font-weight: bold;padding-left: 8rpx;">{{userInfo.giftWater}}</view>
				</view>
				<view class="tips" v-if="qrcode && qrcode.stock">
					<view>*当前二维码余额:</view>
					<view style="color: #FB8C00;font-weight: bold;padding-left: 8rpx;">{{qrcode.stock}}</view>
				</view>
				<view class="tips" v-if="qrcode && qrcode.canAddCount">
					<view>*当前还可转入:</view>
					<view style="color: #FB8C00;font-weight: bold;padding-left: 8rpx;">{{qrcode.canAddCount}}</view>
				</view>
				<view class="tips" v-else>
					<view>*当前还可转入:</view>
					<view style="color: #FB8C00;font-weight: bold;padding-left: 8rpx;">{{userInfo.giftWater<1000?userInfo.giftWater:1000}}</view>
				</view>
			</view>
		</neil-modal>
	</view>
</template>

<script>
	// #ifdef H5 || APP-PLUS
	import uQRCode from '@/js_sdk/Sansnn-uQRCode/uqrcode.js'
	// #endif
	// #ifdef APP-PLUS
	import {
		HTTP_H5_URL
	} from '@/config/app.js';
	// #endif
	import {
		getUserInfo,
		spreadBanner,
		qrcodeList,
		qrcodeSave
	} from '@/api/user.js';
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		mapGetters
	} from "vuex";
	// #ifdef MP
	import {
		base64src
	} from '@/utils/base64src.js'
	import {
		getQrcode
	} from '@/api/api.js';
	// #endif
	import {setThemeColor} from '@/utils/setTheme.js'
	import neilModal from '@/components/neil-modal/neil-modal.vue';
	import {
		imageBase64
	} from "@/api/public";
	export default {
		components: {
			neilModal
		},
		data() {
			return {
				addCount: '',
				grantCount: '',
				show: false,
				imgUrls: [],
				indicatorDots: false,
				circular: false,
				autoplay: false,
				interval: 3000,
				duration: 500,
				swiperIndex: 0,
				spreadList: [],
				poster: '',
				qrcodeSize: 1000,
				PromotionCode: '',
				base64List: [],
				canvasStatus: true, //海报绘图标签
				bgColor:'#e93323',
				qrcode: null,
			};
		},
		computed: mapGetters(['isLogin', 'uid', 'userInfo']),
		watch: {
			isLogin: {
				handler: function(newV, oldV) {
					if (newV) {
						this.userSpreadBannerList();
					}
				},
				deep: true
			}
		},
		onLoad() {
			
			this.getGrcode()
		},
		/**
		 * 用户点击右上角分享
		 */
		// #ifdef MP
		onShareAppMessage: function() {
			return {
				title: this.userInfo.nickname + '-拉新海报',
				imageUrl: this.spreadList[0].pic,
				path: `/pages/users/login/index?qrcode=${this.qrcode.id}&invest=${this.userInfo.investCode}`,
			};
		},
		// #endif
		onReady() {},
		methods: {
			save() {
				this.show=false
				if (this.addCount == '') {
					this.$util.Tips({
						title:  "请填写转入的赠送水票数量"
					});
					return
				}
				if (!(this.grantCount <11 && this.grantCount>0)) {
					this.$util.Tips({
						title:  "领取的赠送水票数量在0-11之间"
					});
					return
				}
				let model = {
					addCount:this.addCount,
					grantCount:this.grantCount,
				}
				if (this.qrcode) {
					model.id = this.qrcode.id
				}
				
				qrcodeSave(model).then(res => {
					this.getGrcode()
					this.getUserInfo()
				})
			},
			getGrcode() {
				qrcodeList({
				}).then(res => {
					this.qrcode = (res.data || [])[0]
					if (this.qrcode) {
						this.grantCount = this.qrcode.grantCount
					}
					if (this.qrcode && this.spreadList.length == 0) {
						this.bgColor = setThemeColor();
						if (this.isLogin) {
							this.userSpreadBannerList();
						} else {
							toLogin();
						}
					}
				}).catch(err => {
				});
			},
			userSpreadBannerList: function() {
				let that = this;
				uni.showLoading({
					title: '获取中',
					mask: true,
				})
				let href = '';
				href = window.location.href.split('/pages')[0];
				spreadBanner({
					page: 1,
					limit: 5,
					gid:75,
					url: href + `/pages/users/login/index?qrcode=${this.qrcode.id}&invest=${this.userInfo.investCode}`,
					createQr:true,
				}).then(res => {
					uni.hideLoading();
					that.$set(that, 'spreadList', res.data);
					// that.getImageBase64(res.data);
				}).catch(err => {
					uni.hideLoading();
				});
			},
			getImageBase64: function(images) {
				uni.showLoading({
					title: '海报生成中',
					mask: true
				});
				let that = this;
				// #ifdef H5
				let spreadList = []
				// 生成一个Promise对象的数组
				images.forEach(item => {
					const oneApi = imageBase64({
						url: item.pic
					}).then(res => {
						return res.data.code;
					})
					spreadList.push(oneApi)
				})
				Promise.all(spreadList).then(result => {
					that.$set(that, 'base64List', result);
					that.make();
					that.setShareInfoStatus();
				})
				// #endif

				// #ifdef MP || APP-PLUS
				that.base64List = images.map(item => {
					return item.pic
				});
				// #endif

				// #ifdef MP
				that.getQrcode();
				// #endif
				// #ifdef APP-PLUS
				that.make();
				// #endif
			},
			// 小程序二维码
			getQrcode() {
				let that = this;
				let data = {
					pid: that.uid,
					path: 'pages/index/index'
				}
				let arrImagesUrl = "";
				uni.downloadFile({
					url: this.base64List[0],
					success: (res) => {
						arrImagesUrl = res.tempFilePath;
					}
				});
				getQrcode(data).then(res => {
					base64src(res.data.code,Date.now(), res => {
						that.PromotionCode = res;
						setTimeout(() => {
							that.PosterCanvas(arrImagesUrl, that.PromotionCode, that.userInfo.nickname, 0);
						}, 1000);
					});
				}).catch(err => {
					uni.hideLoading();
					that.$util.Tips({
						title: err
					});
					that.$set(that, 'canvasStatus', false);
				});
			},
			// 生成二维码；
			make() {
				let that = this;
				let href = '';
				// #ifdef H5
				href = window.location.href.split('/pages')[0];
				// #endif
				// #ifdef APP-PLUS
				href = HTTP_H5_URL;
				let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
				let curRoute = routes[routes.length - 1].route //获取当前页面路由
				let curParam = routes[routes.length - 1].options; //获取路由参数
				// #endif
				uQRCode.make({
					canvasId: 'qrcode',
					text: href + `/pages/users/login/index?qrcode=${this.qrcode.id}&invest=${this.userInfo.investCode}`,
					size: this.qrcodeSize,
					margin: 10,
					success: res => {
						that.PromotionCode = res;
						setTimeout(() => {
							that.PosterCanvas(this.base64List[0], that.PromotionCode, that.userInfo.nickname, 0,this.userInfo);
						}, 1000);
					},
					complete: (res) => {},
					fail: res => {
						uni.hideLoading();
						that.$util.Tips({
							title: '海报二维码生成失败！'
						});
					}
				})
			},
			PosterCanvas: function(arrImages, code, nickname, index) {
				let context = uni.createCanvasContext('canvasOne')
				context.clearRect(0, 0, 0, 0);
				let that = this;
				uni.getImageInfo({
					src: arrImages,
					success: function(res) {
						context.drawImage(arrImages, 0, 0, 750, 1190);
						context.save();
						context.drawImage(code, 110, 925, 140, 140);
						context.restore();
						context.setFontSize(28);
						context.fillText(nickname, 270, 955);
						context.fillText(`邀请码：${that.userInfo.investCode}`, 270, 1005);
						context.fillText('邀请您加入', 270, 1055);
						setTimeout(() => {
							context.draw(true, function() {
								uni.canvasToTempFilePath({
									destWidth: 750,
									destHeight: 1190,
									canvasId: 'canvasOne',
									fileType: 'jpg',
									success: function(res) {
										// 在H5平台下，tempFilePath 为 base64
										uni.hideLoading();
										that.spreadList[index].pic = res.tempFilePath;
										that.$set(that, 'poster', res.tempFilePath);
										that.$set(that, 'canvasStatus', false);
									}
								})
							})
							
						}, 100);
					},
					fail: function(err) {
						uni.hideLoading();
						that.$util.Tips({
							title: '无法获取图片信息'
						});
					}
				});
			},
			bindchange(e) {
				let base64List = this.base64List;
				let index = e.detail.current;
				this.swiperIndex = index;
				let arrImagesUrl = "";
				uni.downloadFile({
					url: base64List[index],
					success: (res) => {
						arrImagesUrl = res.tempFilePath;
						setTimeout(() => {
							this.$set(this, 'canvasStatus', true);
							this.PosterCanvas(arrImagesUrl, this.PromotionCode, this.userInfo.nickname,index);
						}, 300);
					}
				});
			},
			// 点击保存海报
			savePhoto:function(url){
				let that = this;
				uni.saveImageToPhotosAlbum({
					filePath: url,
					success: function(res) {
						that.$util.Tips({
							title: '保存成功',
							icon: 'success'
						});
					},
					fail: function(res) {
						that.$util.Tips({
							title: '保存失败'
						});
					}
				}); 
			},
			setShareInfoStatus: function() {
				if (this.$wechat.isWeixin()) {
					let configAppMessage = {
						desc: '拉新海报',
						title: this.userInfo.nickname + '-拉新海报',
						link: `/pages/users/login/index?qrcode=${this.qrcode.id}&invest=${this.userInfo.investCode}`,
						imgUrl: this.spreadList[0].pic
					};
					this.$wechat.wechatEvevt(["updateAppMessageShareData", "updateTimelineShareData"],
						configAppMessage)
				}
			},
			/**
			 * 获取个人用户信息
			 */
			getUserInfo: function() {
				let that = this;
				getUserInfo().then(res => {
					that.$store.commit("UPDATE_USERINFO", res.data);
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	// page {
	// 	background-color: #A2A2A2 !important;
	// 	height: 100vh;
	// 	overflow: auto;
	// }
	.tips{
		padding: 14rpx 0 0 0;
		display: flex;
		align-items: center;
		font-size: 24rpx;
		color: #CC6F35;
		justify-content: end;
	}
	.card{
		background: #FFFFFF;
		box-sizing: border-box;
		padding: 0 60rpx;
		margin-top: 20rpx;
		padding-bottom: 30rpx;
	}
	.item2 {
		padding: 40rpx 0;
		display: flex;
		align-items: center;
	}
	.item{
		height: 120rpx;
		border-bottom: 1rpx solid #D8D8D8;
		display: flex;
		align-items: center;
	}
	.item-title{
		font-size: 28rpx;
		margin-right: 53rpx;
		color: #787E82;
		position: relative;
		&::after{
			content: "*";
			color: red;
			position: absolute;
			top: -5rpx;
			left: -20rpx;
		}
	}
	.item-input {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: end;
		text-align: right;
		color: #868686;
		input {
			font-size: 28rpx;
		}
	}
	.page{
		height: 100vh;
		overflow: auto;
		background-color: #A2A2A2 !important;
	}
	.canvas {
		position: relative;
	}

	.distribution-posters {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.distribution-posters swiper {
		width: 100%;
		height: 1000rpx;
		position: relative;
		margin-top: 40rpx;
	}

	.distribution-posters .slide-image {
		width: 100%;
		height: 100%;
		margin: 0 auto;
		border-radius: 15rpx;
	}

	.distribution-posters .slide-image.active {
		transform: none;
		transition: all 0.2s ease-in 0s;
	}

	.distribution-posters .slide-image.quiet {
		transform: scale(0.8333333);
		transition: all 0.2s ease-in 0s;
	}

	.distribution-posters .keep {
		font-size: 30rpx;
		color: #fff;
		width: 600rpx;
		height: 80rpx;
		border-radius: 50rpx;
		text-align: center;
		line-height: 80rpx;
		margin: 38rpx auto;
		
	}

	.distribution-posters .preserve {
		color: #fff;
		text-align: center;
		margin-top: 38rpx;
	}

	.distribution-posters .preserve .line {
		width: 100rpx;
		height: 1px;
		background-color: #fff;
	}

	.distribution-posters .preserve .tip {
		margin: 0 30rpx;
	}
	.invitation-logo{
		display: flex;
		flex: 1;
		align-items: center;
		justify-content: center;
		height: 86rpx;
		background-color: $theme-color;
		border-radius: 120rpx;
		color: #FFFFFF;
		font-size: 30rpx;
	}
</style>
